package com.springboot.blog.loginQQ;

import com.google.gson.Gson;
import com.springboot.blog.beans.User;
import com.springboot.blog.beans.dto.QQDTO;
import com.springboot.blog.beans.dto.QQOpenidDTO;
import com.springboot.blog.config.utils.HttpsUtils;
import com.springboot.blog.dao.AdminUserDao;
import com.springboot.blog.dao.UserDao;
import com.springboot.blog.properties.OAuthProperties;
import com.springboot.blog.service.AdminUserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class LoginQQController {


    private Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    private OAuthProperties oauth;
    @Resource
    private UserDao userDao;
    @Resource
    private AdminUserServiceImpl adminUserService;


    //QQ登陆对外接口，只需将该接口放置html的a标签href中即可
    @GetMapping("/login/qq")
    public void loginQQ(HttpServletResponse response) {
        try {
            response.sendRedirect(oauth.getQQ().getCode_callback_uri() + //获取code码地址
                    "?client_id=" + oauth.getQQ().getClient_id()//appid
                    + "&state=" + UUID.randomUUID() + //这个说是防攻击的，就给个随机uuid吧
                    "&redirect_uri=" + oauth.getQQ().getRedirect_uri() +//这个很重要，这个是回调地址，即就收腾讯返回的code码
                    "&response_type=code");//授权模式，授权码模式
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/login/jb")
    public String loginjb(HttpServletRequest request){
        String  userName = (String) request.getServletContext().getAttribute("userName");
        userDao.updateAppid(userName,null,0);
        return "redirect:/user/userindex";
    }

    //接收回调地址带过来的code码
    @GetMapping("/authorize/qq")
    public String authorizeQQ(HttpServletRequest request, Map<String, String> msg, String code) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        params.put("redirect_uri", oauth.getQQ().getRedirect_uri());
        params.put("client_id", oauth.getQQ().getClient_id());
        params.put("client_secret", oauth.getQQ().getClient_secret());
        //获取access_token如：access_token=9724892714FDF1E3ED5A4C6D074AF9CB&expires_in=7776000&refresh_token=9E0DE422742ACCAB629A54B3BFEC61FF
        //TODO 其实整合NUTZ后，可以不使用HttpUtils工具类，并去掉pom中httpasyncclient、httpmime依赖，使用NUTZ自带HTTP工具
        String result = HttpsUtils.doGet(oauth.getQQ().getAccess_token_callback_uri(), params);
        //对拿到的数据进行切割字符串
        String[] strings = result.split("&");
        //切割好后放进map
        Map<String, String> reulsts = new HashMap<>();
        for (String str : strings) {
            String[] split = str.split("=");
            if (split.length > 1) {
                reulsts.put(split[0], split[1]);
            }
        }
        //到这里access_token已经处理好了
        //下一步获取openid，只有拿到openid才能拿到用户信息
        String openidContent = HttpsUtils.doGet(oauth.getQQ().getOpenid_callback_uri() + "?access_token=" + reulsts.get("access_token"));
        //接下来对openid进行处理
        //截取需要的那部分json字符串
        String openid = openidContent.substring(openidContent.indexOf("{"), openidContent.indexOf("}") + 1);
        Gson gson = new Gson();
        //将返回的openid转换成DTO
        QQOpenidDTO qqOpenidDTO = gson.fromJson(openid, QQOpenidDTO.class);
        String  userName = (String) request.getServletContext().getAttribute("userName");
        System.out.println("==============OpenId "+qqOpenidDTO.getOpenid());
        User user = null;
        try {
            user = userDao.queryByUsername(userName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (userName!=null&&user.getAvailable()==0) {
            try {
                params.clear();
                params.put("access_token", reulsts.get("access_token"));//设置access_token
                params.put("openid", qqOpenidDTO.getOpenid());//设置openid
                params.put("oauth_consumer_key", qqOpenidDTO.getClient_id());//设置appid
                String userInfo = HttpsUtils.doGet(oauth.getQQ().getUser_info_callback_uri(), params);
                QQDTO qqDTO = gson.fromJson(userInfo, QQDTO.class);//json转换成dto
                userDao.updateAppid(userName, qqOpenidDTO.getOpenid(), 1);
                return "redirect:/user/userindex";
            } catch (Exception e) {
                e.printStackTrace();
                return "redirect:/user/userindex";
            }
        }
            User user1 = userDao.selectUserByOpenid(qqOpenidDTO.getOpenid());
        if (user1!=null){
            request.getSession().setAttribute("userName",user1.getUsername());
            request.getServletContext().setAttribute("userName",user1.getUsername());
            AuthenticationInfo info = new SimpleAuthenticationInfo(user1.getUsername(),user1.getPassword(), ByteSource.Util.bytes(user1.getPwdsalt()),"myUserRealm");
            return "redirect:/user/userindex";
        }else {
            return "redirect:/user";
        }
    }


}
